// 首先引入axios和上一步封装的cookie方法
import axios from 'axios';
import type { AxiosRequestHeaders, AxiosResponse } from 'axios';
// import { useStore } from '@/store/modules/globalLoading';
import { message } from '@/utils';
import useLoading from '@/hooks/loading';
import { useUserStore, useAppStore } from '@/store';
const { setLoading } = useLoading();
const { VITE_API_QQMAP_URL } = import.meta.env;
const mapKey = ref('B4CBZ-SD3LL-CPAPH-ELXNF-GSRYQ-B6FFD');
const service = axios.create({
  baseURL: VITE_API_QQMAP_URL,
});
//http response 拦截
service.interceptors.response.use(
  async (res: any) => {
    const status = res.data.code || res.data.status;
    console.log('🚀 ~ status:', status);
    const msg = res.data.msg || res.data.message;
    if (status == 0) return Promise.resolve(res.data);
    else if (status >= 500 && status < 600) {
      console.log('🚀 ~ file: request.ts:40 ~ msg:', msg);
      message({
        type: 'error',
        content: msg,
      });
      return Promise.reject(new Error(msg));
    } else {
      message({
        type: 'error',
        content: msg,
      });
      return Promise.reject(new Error(msg));
    }
  },
  (error) => {
    console.log('🚀 ~ file: request.ts:64 ~ error:', error);
    message({
      type: 'error',
      content: '请求错误',
      // cb: () => location.reload(),
    });
    return Promise.reject(new Error(error));
  }
);

interface Response<T> {
  status: number;
  data: T;
  msg: string;
  result?: any;
  success: boolean;
}
const request = <T = any>(
  type: 'get' | 'post' | 'delete' | 'put',
  api: string,
  data: object,
  loading: boolean = type != 'get',
  headers: AxiosRequestHeaders = {}
): Promise<Response<T>> => {
  if (loading) setLoading(true);
  return new Promise((resolve, reject) => {
    const query =
      type === 'get' ? { params: { key: mapKey.value, ...data } } : data;
    //@ts-ignore;
    service[type](api, query, { headers })
      .then((res: AxiosResponse<Response<T>>) =>
        resolve(Promise.resolve(res as any as Response<T>))
      )
      .catch((err: AxiosResponse) => reject(err))
      .finally(() => loading && setLoading(false));
  });
};
type Requestoptions = {
  url: string;
  data?: any;
  loading?: boolean;
  headers?: any;
};
/**
 * get请求
 * @param  query 请求配置
 * @param data 请求参数
 * @param  success 成功回调
 * @param  err 失败回调
 */

const get = <T = any>(
  { url, loading = false, data = {}, headers = {} }: Requestoptions,

  success?: (response: Response<T>) => void,
  err?: Function
): Promise<Response<T>> => {
  return new Promise((reslove, reject) => {
    request<T>('get', url, data, loading, headers)
      .then((res) => {
        if (res.status == 0) {
          success?.(res);
          reslove(res);
        } else {
          message({
            type: 'error',
            content: res.msg,
          });
          err?.(res);
          reject(res);
        }
      })
      .catch((res) => {
        console.log(res);

        err?.({ msg: res.message });
        reject({ msg: res.message });
      });
  });
};

export { get, request, service };
